package com.gxg.newdemo1.mynewdamo1.dayin;

import android.os.Environment;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class FileUtility {
	public static String computeFileMd5(String filePath){
		String value = null;
		FileInputStream in = null;
		try {
			File file = new File(filePath);
			if(!file.exists()){
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
	        in = new FileInputStream(file);
	        MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
	        MessageDigest md5 = MessageDigest.getInstance("MD5");
	        md5.update(byteBuffer);
	        BigInteger bi = new BigInteger(1, md5.digest());
	        value = bi.toString(16);
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	            if(null != in) {
	                try {
	                in.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    return value;
	}
	
	/**
	 * 读取文件内容成字符串  syl
	 * @param filePath
	 * @return
	 */
	public static String readFile2Str(String filePath){
		String value = null;
		File file = new File(filePath);
		if(!file.exists()){
			return null;
		}
		
		FileInputStream in = null;
		try{
			in = new FileInputStream(file);
			byte b[] = new byte[(int) file.length()];
			in.read(b);
			value = new String(b);
		}catch(Exception e){
			
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
				}
			}
		}
		
		return value;
	}
	
	
	
	/**
	 * 保存上传文件 syl
	 * 
	 *            文件项目
	 * @param savePath
	 *            保存文件的全路径
	 * @throws IOException
	 */
	public static void saveFile(InputStream inputStream, String savePath)
			throws IOException {
		if (savePath == null) {
			return;
		}
		File outFile = new File(savePath);
		File outPath = outFile.getParentFile();
		if (!outPath.exists()) {
			outPath.mkdirs();
		}
		if (!outFile.exists()) {
			outFile.createNewFile();
		}
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(inputStream);
			out = new BufferedOutputStream(new FileOutputStream(outFile));
			byte[] buff = new byte[1024];
			int length = 0;
			while ((length = in.read(buff)) > 0) {
				out.write(buff, 0, length);
				out.flush();
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
			}
		}
	}
	
	/**
	 * 把文件加载到字节数组
	 * 
	 * @param fileName
	 */
	public static  byte[] loadFile2Bytes(String fileName) throws Exception {
		InputStream in = null;
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				return null;
			}
			in = new FileInputStream(fileName);
			int fileLength = (int) file.length();
			byte[] buff = new byte[fileLength];
			in.read(buff, 0, fileLength);

			return buff;
		} catch (Exception ex) {
			throw ex;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
			}
		}
	}
	
	/**
	 * 保存文件 
	 * @param dataImageByte  二进制流
	 * @param savePath  保存目录
	 * @throws IOException
	 */
 	public static void saveFileByBytes( byte[] dataImageByte , String savePath)
 			throws IOException {
 		if (savePath == null) {
 			return;
 		}
 		File outFile = new File(savePath);
 		if(!outFile.exists()){
 			outFile.getParentFile().mkdirs();
 			outFile.createNewFile();
 		}
 		OutputStream out = null;
 		try {
 			out = new BufferedOutputStream(new FileOutputStream(outFile));
 			byte[] buff = new byte[1024];
 			out.write(dataImageByte, 0, dataImageByte.length);
 			out.flush();
 		} catch (IOException ex) {
 			throw ex;
 		} finally {
 			
 			try {
 				if (out != null) {
 					out.close();
 				}
 			} catch (Exception ex) {
 			}
 		}
 	}
	
//	 /**
//	  * 获取web 文件 二进制流
//	  * @param fileUrl web路径  http://192.168.1.102:88/oaop/....
//	  *
//	  * @return
//	  */
//	  public static  byte[] getWebFileBytes(String fileUrl) {
//	    try {
//	      URL url = new URL(fileUrl);
//	      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//	      conn.setRequestProperty("Cookie", "JSESSIONID=" + Main.JSESSIONID);//设置cookie
//	      conn.setRequestMethod("GET");
//
//	      conn.setDoOutput(true);// 允许输出
//	      conn.setRequestProperty("connection", "keep-alive"); // 客户端到服务器端的连接持续有效
//	      conn.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
//	      conn.setRequestProperty("accept-encoding", "gzip,deflate");//设置 gzip的请求头
//
//	      conn.setConnectTimeout(5 * 1000);
//	      conn.connect();
//	      InputStream in = conn.getInputStream();
//	      ByteArrayOutputStream bos = new ByteArrayOutputStream();
//	      byte[] buffer = new byte[1024];
//	      int len = 0;
//	      while ((len = in.read(buffer)) != -1) {
//	          bos.write(buffer, 0, len);
//	      }
//	      byte[] dataByte = bos.toByteArray();
//	      return dataByte;
//	    } catch (Exception e) {
//	      // TODO Auto-generated catch block
//	        e.printStackTrace();
//	    }
//	    return null;
//	  }
	  
	 /**
	  * 获取内存卡路径
	  * @return
	  */
	 public static File getSDPath(){
		 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
	      {
	          /* 得到SD卡得路径 */
	          File mRecAudioPath = Environment.getExternalStorageDirectory();
			  mRecAudioPath = new File(mRecAudioPath.getAbsolutePath()+"/Android/data/com.zatp.app/");
	          return mRecAudioPath;
	      }
		  return  null;
	 }

	/**
	 * 获取文件名称的拓展名
	 * @param fileName 文件名称
	 * @return
     */
	public static String getExtensionName(String fileName){
		String end = fileName.substring(fileName.lastIndexOf(".")+ 1,fileName.length()).toLowerCase();
		return end;
	}
	  
}
